import { Middleware, Context } from 'koa';
import { APIError } from './restful';
import * as jwt from 'jsonwebtoken';
import config from '../config';

export const sign = (data: Object) => {
  return new Promise((resolve, reject) => {
    jwt.sign(data, config.jwt.secret, {
      expiresIn: config.jwt.life,
      noTimestamp: true
    }, (err, token) => {
      if (err)
        return reject(err);
      resolve(token);
    });
  });
};

export const signSync = (data: Object) => {
  return jwt.sign(data, config.jwt.secret, {
    expiresIn: config.jwt.life,
    noTimestamp: true,
  });
};

export const verify = (token: string) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, config.jwt.secret, (err, token) => {
      if (err)
        return reject(err);
      resolve(token);
    });
  });
};

export const auth: Middleware = async (ctx: Context, next) => {
  try {
    const authorization: string = ctx.headers.authorization;
    // authorization: Bearer xxxxxxxxxxx
    const token = authorization.slice('Bearer '.length);
    ctx.state.user = await verify(token);
  } catch (err) {
    throw new APIError('auth: auth fail', '身份验证失败');
  }
  await next();
};
